
/*
获得商品等
 */

import 'package:reabampos/src/reabam/operation/bean/barcode_rule/Response_barcode_rule.dart';
import 'package:reabampos/src/reabam/operation/bean/h5_search_good.dart';
import 'package:reabampos/src/reabam/operation/db/objectbox.dart';
import 'package:reabampos/src/reabam/operation/rb_api.dart';
import 'package:reabampos/src/reabam/operation/rb_config.dart';
import 'package:reabampos/src/reabam/ui/pagestate_main_webview.dart';
import 'package:reabampos/src/reabam/utils/rb_aliyun_log.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_aliyun_log.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';
import 'package:xsdk_flutter_plugin/xsdk_flutter_plugin.dart';

abstract class SupportGetGoodItems {


  //离线商品
  static void searchGoodItems(
      XPageState statePage,
      dynamic data,
      {
        bool isSearchMainItem=true, //默认搜索返回主商品(单规格商品,多规格主商品)
        required XFunctionObjectBoxCallback callback,
      }
      )
  {

    try{
      BeanH5RequestPageGoods beanH5RequestPageGoods;
      if(data is String){
        beanH5RequestPageGoods=BeanH5RequestPageGoods.fromJson(XJsonUtils.json2Map(data));
      }else if(data is BeanH5RequestPageGoods){
        beanH5RequestPageGoods=data;
      }else{
        beanH5RequestPageGoods=BeanH5RequestPageGoods.fromJson(data??{});
      }

      //检查barcode规则
      _checkBarcodeSearchRule1(statePage,beanH5RequestPageGoods,isSearchMainItem:isSearchMainItem,callback:callback);

    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('offlineGoodItems'),'$e');
    }

  }


  //检查barcode规则
  static void _checkBarcodeSearchRule1(
      XPageState statePage,
      BeanH5RequestPageGoods beanH5RequestPageGoods,
      {
        bool isSearchMainItem=true, //默认搜索返回主商品(单规格商品,多规格主商品)
        required XFunctionObjectBoxCallback callback
      }

      ) async{

    if(!XStringUtils.isEmpty(beanH5RequestPageGoods.sword)){

      String barcodeRuleJson=XSharePreferencesUtils.getString(RBConfigs.SP_barcode_search_rule);

      if(XStringUtils.isEmpty(barcodeRuleJson)){
        //重新获取规则

        ResponseBarcodeRule? response= await RBBaseApi.getBarcodeSearchRule();
        ResponseBarcodeRuleDataBean? data=response?.data;
        if(data!=null){
          //
          List<BarcodeSearchRulesBean>? barcodeSearchRules=data.barcodeSearchRules;
          barcodeSearchRules ??= [];
          //
          XSharePreferencesUtils.saveString(RBConfigs.SP_barcode_search_rule,XJsonUtils.obj2Json(barcodeSearchRules));

          //
          _handleBarcodeSearchRule(beanH5RequestPageGoods,isSearchMainItem:isSearchMainItem,callback:callback);

        }else{
          statePage.toast('${response?.msg}');
        }

      }else{
        _handleBarcodeSearchRule(beanH5RequestPageGoods,isSearchMainItem:isSearchMainItem,callback:callback);
      }


    }else{
      //查找商品
      _getPageItemList(
          beanH5RequestPageGoods,
          false,
          0,
          '',
          '',
          0,
          0,
          0,
          isSearchMainItem:isSearchMainItem,
          callback:callback
      );
    }


  }


  //处理搜索key规则
  static void _handleBarcodeSearchRule(
      BeanH5RequestPageGoods beanH5RequestPageGoods,
      {
        bool isSearchMainItem=true, //默认搜索返回主商品(单规格商品,多规格主商品)
        required XFunctionObjectBoxCallback callback,
      }
      ){
    String ruleJson=XSharePreferencesUtils.getString(RBConfigs.SP_barcode_search_rule);

    XLogUtils.printLog('---ruleJson=$ruleJson');
    List<BarcodeSearchRulesBean> barcodeSearchRules=[];
    List<dynamic> barcodeSearchRules1=XJsonUtils.json2List(ruleJson);
    for(dynamic iitem in barcodeSearchRules1){
      BarcodeSearchRulesBean jsonItem=BarcodeSearchRulesBean.fromJson(iitem);
      barcodeSearchRules.add(jsonItem);
    }

    if(barcodeSearchRules.isEmpty){
      //查找商品
      _getPageItemList(
          beanH5RequestPageGoods,
          false,
          0,
          '',
          '',
          0,
          0,
          0,
          isSearchMainItem:isSearchMainItem,
          callback:callback
      );
    }else{
      //检测规则
      bool isFixRule=false;
      for(BarcodeSearchRulesBean ruleItem in barcodeSearchRules){
        String? skuPrefix=ruleItem.skuPrefix;
        int ruleType=ruleItem.ruleType;
        if(!XStringUtils.isEmpty(skuPrefix)
            &&(ruleType==2||ruleType==3||ruleType==5)
        ){

          List<String> arr = skuPrefix!.split(";");
          for(String iitemR in arr){
            if(!XStringUtils.isEmpty(iitemR)){
              isFixRule=_handleSkuPrefix(beanH5RequestPageGoods,ruleItem,iitemR,isSearchMainItem:isSearchMainItem,callback:callback);
              if(isFixRule){
                break;
              }
            }

          }

          if(isFixRule){
            break;
          }
        }
      }

      //不是称重码,金额码,查找商品
      if(!isFixRule){
        _getPageItemList(
            beanH5RequestPageGoods,
            false,
            0,
            '',
            '',
            0,
            0,
            0,
            isSearchMainItem:isSearchMainItem,
            callback:callback
        );
      }

    }
  }


  //搜索key匹配前缀
  static bool _handleSkuPrefix(
      BeanH5RequestPageGoods beanH5RequestPageGoods,
      BarcodeSearchRulesBean ruleItem,
      String singleSkuPrefix,
      {
        bool isSearchMainItem=true, //默认搜索返回主商品(单规格商品,多规格主商品)
        required XFunctionObjectBoxCallback callback,
      }
      )
  {

    int ruleType=ruleItem.ruleType;
    String searchKeyWord=beanH5RequestPageGoods.sword??'';
    XLogUtils.printLog('---searchKeyWord=$searchKeyWord,singleSkuPrefix=$singleSkuPrefix');
    //查看关键字是否符合前缀
    if(searchKeyWord.startsWith(singleSkuPrefix)){

      int skuStartDigit = ruleItem.skuStartDigit; //条码开始位
      int skuEndDigit = ruleItem.skuEndDigit; //条码结束位

      int customizeStartDigit = ruleItem.customizeStartDigit; //重量开始位
      int customizeEndDigit = ruleItem.customizeEndDigit; //重量结束位
      int amountEndDigit = ruleItem.amountEndDigit; //金额结束位
      int amountStartDigit = ruleItem.amountStartDigit; //金额开始位

      double reverseDecimalCount = ruleItem.reverseDecimalCount==null?0:double.parse(ruleItem.reverseDecimalCount.toString()); //反算保留小数点位数
      double weightDecimalCount = ruleItem.weightDecimalCount==null?0:double.parse(ruleItem.weightDecimalCount.toString()); //反算保留小数点位数
      double amountDecimalCount = ruleItem.amountDecimalCount==null?0:double.parse(ruleItem.amountDecimalCount.toString()); //反算保留小数点位数

      //
      String sword="";
      String weight="";
      String amount="";

      //api返回字符串截取从1开始(按客户)
      if (ruleType==2){
        //条码重量码 2
        if(searchKeyWord.length >= customizeEndDigit){
          //匹配了前缀，开始拆解条码和金额
          sword = searchKeyWord.substring(skuStartDigit-1, skuEndDigit);
          amount = searchKeyWord.substring(customizeStartDigit-1, customizeEndDigit);
        }

      }else if (ruleType==3){
        //条码金额码 3
        if(searchKeyWord.length >= customizeEndDigit){
          //匹配了前缀，开始拆解条码和金额
          sword = searchKeyWord.substring(skuStartDigit-1, skuEndDigit);
          amount = searchKeyWord.substring(customizeStartDigit-1, customizeEndDigit);
        }

      }else if (ruleType==5){
        //条码金额码+重量码 5

        //检查长度是否够
        if (searchKeyWord.length >= amountEndDigit && amountEndDigit > 0) {

          //匹配了前缀，开始拆解条码和金额
          sword = searchKeyWord.substring(skuStartDigit-1, skuEndDigit);
          weight = searchKeyWord.substring(customizeStartDigit-1, customizeEndDigit);
          amount = searchKeyWord.substring(amountStartDigit-1, amountEndDigit);

        }

      }

      XLogUtils.printLog("---匹配到符合的前缀,singleSkuPrefix=$singleSkuPrefix,ruleType=$ruleType,sword=$sword,weight=$weight,amount=$amount");

      beanH5RequestPageGoods.sword=sword;
      //查找商品
      _getPageItemList(
          beanH5RequestPageGoods,
          true,
          ruleType,
          amount,
          weight,
          XNumberUtils.d2int(reverseDecimalCount),
          XNumberUtils.d2int(amountDecimalCount),
          XNumberUtils.d2int(weightDecimalCount),
          isSearchMainItem:isSearchMainItem,
          callback:callback
      );

      return true;

    }

    return false;


  }


  //搜索商品
  static void _getPageItemList(
      BeanH5RequestPageGoods beanH5RequestPageGoods,
      bool isFixBarcodeRule,
      int ruleType,
      String amount,
      String weight,
      int reverseDecimalCount,
      int amountDecimalCount,
      int weightDecimalCount,
      {
        bool isSearchMainItem=true, //默认搜索返回主商品(单规格商品,多规格主商品)
        required XFunctionObjectBoxCallback callback,
      }
      ){
    //
    XObjectBoxUtils.getBeanOfflineDBGoodList(
        pageIndex:beanH5RequestPageGoods.pageIndex,
        pageSize:beanH5RequestPageGoods.pageSize,
        fCode:beanH5RequestPageGoods.fCode,
        keyword:beanH5RequestPageGoods.sword,
        isFixBarcodeRule:isFixBarcodeRule,
        ruleType:ruleType,
        amount:amount,
        weight:weight,
        reverseDecimalCount:reverseDecimalCount,
        amountDecimalCount:amountDecimalCount,
        weightDecimalCount:weightDecimalCount,
        isSearchMainItem:isSearchMainItem,
        callback: callback
    );
  }

  //查找商品(简化)
  static void getGoodItems_simpleJson(
      XPageState statePage,
      dynamic data,
      XFunctionObjectBoxCallback callback){

    Future((){

      try{
        BeanH5RequestPageGoods beanH5RequestPageGoods;
        if(data is String){
          beanH5RequestPageGoods=BeanH5RequestPageGoods.fromJson(XJsonUtils.json2Map(data));
        }else if(data is BeanH5RequestPageGoods){
          beanH5RequestPageGoods=data;
        }else{
          beanH5RequestPageGoods=BeanH5RequestPageGoods.fromJson(data??{});
        }

        //test...
        //beanH5RequestPageGoods.sword='JE01089033000';

        if(XStringUtils.isEmpty(beanH5RequestPageGoods.fCode) && !XStringUtils.isEmpty(beanH5RequestPageGoods.sword)){
          //适配搜索(支持重量码,金额码)
          XLogUtils.printLog('---getGoodItems_simpleJson,适配搜索,支持重量码,金额码,sword=${beanH5RequestPageGoods.sword}');
          searchGoodItems(statePage,beanH5RequestPageGoods,callback: callback);
        }else{
          //结果json
          ItemListResponse response=XObjectBoxUtils.getGoodItems_simpleJson(
              pageIndex:beanH5RequestPageGoods.pageIndex,
              pageSize:beanH5RequestPageGoods.pageSize,
              fCode:beanH5RequestPageGoods.fCode,
              keyword:beanH5RequestPageGoods.sword
          );

          //
          callback(response.toJson());
        }

      }catch(e){
        XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('getItemListCallbackSimpleJson'),'$e');
      }

    });

  }
  //查找商品(简化)
  static void getAiRecognitionItemSimpleJson(
      Map<String, dynamic> responseMap,
      XFunctionResultCallback callback
      )
  {

    Future((){
      try{

        List<dynamic> data=responseMap['data']??[];

        for(dynamic item in data){
          //label实际为itemId
          String itemId=item['label'];
          XLogUtils.printLog('---aiRecognitionImage,label=$itemId');

          //结果json
          ItemListResponse response=XObjectBoxUtils.getGoodItems_simpleJson(
            pageIndex:1,
            pageSize:20,
            fCode:null,
            keyword:itemId,
          );

          if(response.items!=null && response.items!.length!=0){
            item['prediction']['items']=response.items![0];
          }

        }

        String json=XJsonUtils.obj2Json(responseMap);
        callback(json);

      }catch(e){
        XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('getItemListCallbackSimpleJson'),'$e');
      }

    });



  }


  //离线商品
  static void getGoodItemDetail(dynamic data,XFunctionObjectBoxCallback callback){
    String itemId=data??'';
    //查找条件
    XObjectBoxUtils.getGoodItemDetail(
        itemId:itemId,
        callback: callback
    );
  }

  //获得离线数据:规格分页数据(异步处理)ok
  static void getSpecList(dynamic data,XFunctionObjectBoxCallback callback){

    BeanH5RequestPageGoods beanH5RequestPageGoods;
    if(data is String){
      beanH5RequestPageGoods=BeanH5RequestPageGoods.fromJson(XJsonUtils.json2Map(data));
    }else{
      beanH5RequestPageGoods=BeanH5RequestPageGoods.fromJson(data??{});
    }

    //查找条件
    XObjectBoxUtils.getSpecItemList(beanH5RequestPageGoods.specIds,callback);

  }
  //获得离线数据:规格(异步处理)ok
  static void getSpecItem0(dynamic data,XFunctionObjectBoxCallback callback){

    BeanH5RequestPageGoods beanH5RequestPageGoods;
    if(data is String){
      beanH5RequestPageGoods=BeanH5RequestPageGoods.fromJson(XJsonUtils.json2Map(data));
    }else{
      beanH5RequestPageGoods=BeanH5RequestPageGoods.fromJson(data??{});
    }
    //查找条件
    XObjectBoxUtils.getSpecItem(beanH5RequestPageGoods.specId??'',callback);

  }

  //获得离线数据:商品分类
  static String getOfflineGoodType(){
    String json =XSharePreferencesUtils.getString('${RBConfigs.SP_Pos_OfflineDB_goodsType}${XSharePreferencesUtils.getString(RBConfigs.SP_companyId)}');
    return json;
  }

  //获得离线数据:支付方式
  static String getPayTypeList(){
    String json =XSharePreferencesUtils.getString(RBConfigs.SP_Pos_OfflineDB_payType+XSharePreferencesUtils.getString(RBConfigs.SP_companyId));
    return json;
  }
  //获得离线数据:购物车
  static String getOfflineShopCart(){
    String json =XSharePreferencesUtils.getString(RBConfigs.SP_Pos_Offline_ShopCart+XSharePreferencesUtils.getString(RBConfigs.SP_companyId));
    return json;
  }
  //保存购物车离线数据
  static void saveOfflineShopCart(String json){
    try{
      XSharePreferencesUtils.saveString(RBConfigs.SP_Pos_Offline_ShopCart+XSharePreferencesUtils.getString(RBConfigs.SP_companyId),json);
    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('saveOfflineShopCart'),'$e');
    }
  }




}